package com.example.sicnuaccountingapp.ui.budget

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.sicnuaccountingapp.R
import com.example.sicnuaccountingapp.data.entity.Budget
import com.example.sicnuaccountingapp.data.entity.Category
import com.example.sicnuaccountingapp.databinding.DialogEditBudgetBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class EditBudgetDialog : DialogFragment() {
    private var _binding: DialogEditBudgetBinding? = null
    private val binding get() = _binding!!

    private val viewModel: BudgetViewModel by viewModels({ requireParentFragment() })
    private var budget: CategoryBudgetInfo? = null
    private var selectedCategory: Category? = null
    private var categories: List<Category> = emptyList()

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        _binding = DialogEditBudgetBinding.inflate(LayoutInflater.from(context))


        return AlertDialog.Builder(requireContext())
            .setTitle(if (budget == null) R.string.add_budget else R.string.edit_budget)
            .setView(binding.root)
            .setPositiveButton(R.string.save, null)
            .setNegativeButton(R.string.cancel, null)
            .create()
            .apply {
                setOnShowListener { dialog ->
                    (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
                        .setOnClickListener {
                            saveBudget()
                        }
                }
                setupCategoryDropdown()
            }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }



    private fun setupCategoryDropdown() {
       lifecycleScope.launch {
            viewModel.categories.collect { newCategories ->
                categories = newCategories
                val adapter = ArrayAdapter(
                    requireContext(),
                    android.R.layout.simple_dropdown_item_1line,
                    categories.map { it.name }
                )
                binding.categoryAutoComplete.setAdapter(adapter)
                setupInitialValues()
            }
        }

        binding.categoryAutoComplete.onItemSelectedListener=object : OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
                val categories = viewModel.categories.value
                if (position in categories.indices) {
                    selectedCategory = categories[position]
                }
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

        }
    }

    private fun setupInitialValues() {
        budget?.let {
            binding.amountEdit.setText(it.budget.amount.toString())
            binding.categoryAutoComplete.setSelection(categories.indexOf(it.category))
            selectedCategory = it.category
        }
    }

    private fun saveBudget() {
        val amountStr = binding.amountEdit.text.toString()
        
//        if (selectedCategory == null) {
//            Toast.makeText(context, R.string.please_select_category, Toast.LENGTH_SHORT).show()
//            return
//        }

        if (amountStr.isBlank()) {
            Toast.makeText(context, R.string.please_input_budget_amount, Toast.LENGTH_SHORT).show()
            return
        }

        val amount = amountStr.toDoubleOrNull()
        if (amount == null || amount <= 0) {
            Toast.makeText(context, R.string.please_input_budget_amount, Toast.LENGTH_SHORT).show()
            return
        }

        if (budget == null) {
            viewModel.addBudget(selectedCategory?.categoryId, amount)
        } else {
            viewModel.updateBudget(budget!!.budget.copy(
                categoryId = selectedCategory?.categoryId,
                amount = amount
            ))
        }

        dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        const val TAG = "EditBudgetDialog"

        fun newInstance(budget: CategoryBudgetInfo? = null): EditBudgetDialog {
            return EditBudgetDialog().apply {
                this.budget = budget
            }
        }
    }
} 